package com.ycy.smartcourseselection.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ycy.smartcourseselection.common.PageParamsDTO;
import com.ycy.smartcourseselection.common.PageResVO;
import com.ycy.smartcourseselection.common.ResCodeEnum;
import com.ycy.smartcourseselection.common.ResData;
import com.ycy.smartcourseselection.dto.course.*;
import com.ycy.smartcourseselection.entity.*;
import com.ycy.smartcourseselection.exception.CustomException;
import com.ycy.smartcourseselection.mapper.ICourseMapper;
import com.ycy.smartcourseselection.utils.CommonUtils;
import com.ycy.smartcourseselection.utils.PageUtils;
import com.ycy.smartcourseselection.utils.WrapperUtils;
import com.ycy.smartcourseselection.vo.course.*;
import com.ycy.smartcourseselection.vo.score.ScoreVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class CourseService extends ServiceImpl<ICourseMapper, Course> {
    Random random = new Random();
    String[] colorList = {"#a393eb", "#ffd3b6", "#a3de83", "#cca8e9", "#70a1d7", "#ffa07a","#3cb371"};  //香芋紫 肉色 翠绿色 浅紫色 蓝色 浅橙色 亮绿色  #a393eb
    PageUtils<Course, CourseVO> coursePageUtils = new PageUtils<>();
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Lazy
    @Resource
    TeacherService teacherService;
    @Lazy
    @Resource
    CoSelectionService coSelectionService;
    @Lazy
    @Resource
    CoManageService coManageService;
    @Resource
    ScManageService scManageService;
    // @Lazy
    // @Resource
    // ScoreService scoreService;

    //恢复课程
    public ResData<Boolean> recoverCourse(String courseId) {
        Course course = new Course();
        course.setId(courseId);
        course.setIsDelete(0);
        return ResData.success(updateById(course));
    }

    //分页查课程信息
    public ResData<PageResVO<CourseVO>> findPageCourses(FindPageCourseDTO findPageCourseDTO) {
        PageParamsDTO pageParamsDTO = findPageCourseDTO.getPageParams();
        FindAllCourseDTO otherParams = findPageCourseDTO.getOtherParams();

        //验证pageNum，pageSize
        Integer pageNum = pageParamsDTO.getPageNum();
        Integer pageSize = pageParamsDTO.getPageSize();
        coursePageUtils.validatePageNumPageSize(pageNum, pageSize);

        String tchName = otherParams.getTchName();
        String workId = otherParams.getWorkId();
        QueryWrapper<Course> courseWrapper = WrapperUtils.buildAllCourseWrapper(otherParams, new QueryWrapper<>());

        //构造教师名字的查询条件
        ArrayList<HashMap<String, String>> workIdList = new ArrayList<>();
        if (StrUtil.isBlank(workId) && StrUtil.isNotBlank(tchName)) {
            QueryWrapper<Teacher> tchWrapper = new QueryWrapper<>();
            tchWrapper.like("name", tchName);
            List<Teacher> tchList = teacherService.list(tchWrapper);
            // List<Teacher> tchList = list(tchWrapper);
            for (Teacher tch : tchList) {
                HashMap<String, String> tchMap = new HashMap<>();
                tchMap.put("name", tch.getName());
                tchMap.put("workId", tch.getWorkId());
                workIdList.add(tchMap);
                courseWrapper.eq(StrUtil.isNotBlank(tch.getWorkId()), "work_id", tch.getWorkId());
            }
        }

        QueryWrapper<Course> newQueryWrapper = coursePageUtils.buildPageQueryWrapper(pageParamsDTO, courseWrapper);

        List<Course> courseList = list(newQueryWrapper);

        ArrayList<CourseVO> VOList = new ArrayList<>();
        ArrayList<String> courseIdList = new ArrayList<>();
        if (workIdList.size() == 0) {
            ArrayList<String> tchWorkIdList = new ArrayList<>();
            for (Course entity : courseList) {
                CourseVO VO = new CourseVO();
                BeanUtil.copyProperties(entity, VO);

                tchWorkIdList.add(entity.getWorkId());

                courseIdList.add(entity.getId());
                try {
                    VOList.add(setCourseVO(entity, VO));
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new CustomException(ResCodeEnum.SERVER_ERROR,"分页查课程信息格式转化失败");
                }
            }
            QueryWrapper<Teacher> tchWrapper = new QueryWrapper<>();
            tchWrapper.select("name","work_id");
            tchWrapper.in(tchWorkIdList.size() != 0,"work_id", tchWorkIdList);
            List<Teacher> tchList = teacherService.list(tchWrapper);   //此处逻辑需要修改，目前是每一个课程信息都要查询一次teacher表,数据库压力大
            for (CourseVO VO : VOList) {
                for (Teacher teacher: tchList) {
                    if(VO.getWorkId().equals(teacher.getWorkId())) VO.setTchName(teacher.getName()); //给课程VO设置教师名称
                }
            }
        } else {
            for (HashMap<String, String> tchMap : workIdList) {
                for (Course entity : courseList) {
                    if (tchMap.get("workId").equals(entity.getWorkId())) {
                        CourseVO VO = new CourseVO();
                        BeanUtil.copyProperties(entity, VO);
                        // VO.setIsSelected(false);
                        courseIdList.add(entity.getId());
                        VO.setTchName(tchMap.get("name"));  //给课程VO设置教师名称
                        try {
                            VOList.add(setCourseVO(entity, VO));
                        } catch (Exception e) {
                            e.printStackTrace();
                            throw new CustomException(ResCodeEnum.SERVER_ERROR,"分页查课程信息格式转化失败");
                        }
                    }
                }
            }
        }
        if (courseIdList.size() == 0) return returnEmptyRes();


        //如果传了学号，那么查询每个课程该学生有没有已选
        String studentId = otherParams.getStudentId();
        if (StrUtil.isNotBlank(studentId)) {
            QueryWrapper<CoSelection> wrapper = new QueryWrapper<>();
            wrapper.eq("student_id", studentId);
            wrapper.in("course_id", courseIdList);
            List<CoSelection> sameList = coSelectionService.list(wrapper);
            for (CourseVO courseVO : VOList) {
                for (CoSelection entity : sameList) {
                    if (courseVO.getId().equals(entity.getCourseId())) courseVO.setSelectedId(entity.getId());
                }
            }
        }

        //构造选课状态的条件
        String nowTime = df.format(new Date());
        Integer courseIsBegin = otherParams.getCourseIsBegin();
        Integer scoreIsBegin = otherParams.getScoreIsBegin();
        ArrayList<CourseVO> beginOrEndCoVOList = new ArrayList<>();
        ArrayList<CourseVO> beginOrEndScVOList = new ArrayList<>();

        QueryWrapper<CoManage> wrapper = new QueryWrapper<>();
        QueryWrapper<ScoreManage> scWrapper = new QueryWrapper<>();
        wrapper.in("course_id", courseIdList);
        scWrapper.in("course_id", courseIdList);
        List<CoManage> coManageList = coManageService.list(wrapper);
        List<ScoreManage> scManageList = scManageService.list(scWrapper);

        for (CourseVO courseVO : VOList) {
            // if (courseIsBegin != null) {
                for (CoManage entity : coManageList) {  //如果课程管理表中没有该课程的记录，就会漏掉,值为null
                    String beginTime = entity.getBeginTime();
                    String endTime = entity.getEndTime();
                    if (courseVO.getId().equals(entity.getCourseId())) {
                        courseVO.setBeginTime(beginTime);
                        courseVO.setEndTime(endTime);
                        if (courseIsBegin != null && courseIsBegin != 1 && courseIsBegin != 0 && courseIsBegin != 2)
                            throw new CustomException(ResCodeEnum.BAD_REQUEST, "选课状态条件值只能为0,1,2");
                        if (CommonUtils.compareDate(nowTime, beginTime) > 0 && CommonUtils.compareDate(nowTime, endTime) < 0) {
                            courseVO.setCourseIsBegin(1);
                            if (courseIsBegin != null && courseIsBegin == 1) beginOrEndCoVOList.add(courseVO);
                        } else {
                            courseVO.setCourseIsBegin(0);
                            if (courseIsBegin != null && courseIsBegin == 0) beginOrEndCoVOList.add(courseVO);
                        }
                    }
                // }
            }


            // if (scoreIsBegin != null) {
                for (ScoreManage entity : scManageList) {  //如果课程管理表中没有该课程的记录，就会漏掉,值为null
                    String beginTime = entity.getBeginTime();
                    String endTime = entity.getEndTime();
                    if (courseVO.getId().equals(entity.getCourseId())) {
                        courseVO.setScBeginTime(beginTime);
                        courseVO.setScEndTime(endTime);
                        if (scoreIsBegin != null && scoreIsBegin != 1 && scoreIsBegin != 0 && scoreIsBegin != 2)
                            throw new CustomException(ResCodeEnum.BAD_REQUEST, "成绩录入状态条件值只能为0,1,2");
                        if (CommonUtils.compareDate(nowTime, beginTime) > 0 && CommonUtils.compareDate(nowTime, endTime) < 0) {
                            courseVO.setScoreIsBegin(1);
                            if (scoreIsBegin != null && scoreIsBegin == 1) beginOrEndScVOList.add(courseVO);
                        } else {
                            courseVO.setScoreIsBegin(0);
                            if (scoreIsBegin != null && scoreIsBegin == 0) beginOrEndScVOList.add(courseVO);
                        }
                    }
                }
            // }

        }
        if (courseIsBegin != null && scoreIsBegin == null) VOList = beginOrEndCoVOList;
        if (scoreIsBegin != null && courseIsBegin == null) VOList = beginOrEndScVOList;
        if (courseIsBegin != null && scoreIsBegin != null) {
            ArrayList<CourseVO> newList = new ArrayList<>();
            for (CourseVO scManage : beginOrEndScVOList) {
                for (CourseVO coManage : beginOrEndCoVOList) {
                    if (scManage.getId().equals(coManage.getId())) {
                        BeanUtil.copyProperties(scManage, coManage);
                        newList.add(coManage);
                    }
                }
            }
            VOList = newList;
        }

        //构造分页结果
        PageResVO<CourseVO> pageResVO = coursePageUtils.getCustomPageResVO(pageNum,pageSize,VOList);

        return ResData.success(pageResVO);
    }

    //增加或修改课程信息
    public ResData<Boolean> saveCourse(CourseDTO courseDTO) {
        boolean isAdd = StrUtil.isBlank(courseDTO.getId());
        String week = courseDTO.getWeek();
        String weekDay = courseDTO.getWeekDay();
        String orderNum = courseDTO.getOrderNum();
        String workId = courseDTO.getWorkId();
        String teachClass = courseDTO.getTeachClass();
        String grade = courseDTO.getGrade();
        String stage = courseDTO.getStage();
        String schoolYear = courseDTO.getSchoolYear();

        if (StrUtil.isBlank(workId)) throw new CustomException(ResCodeEnum.BAD_REQUEST, "教师不能为空");
        if (StrUtil.isBlank(teachClass)) throw new CustomException(ResCodeEnum.BAD_REQUEST, "教学班不能为空");
        if (StrUtil.isBlank(week)) throw new CustomException(ResCodeEnum.BAD_REQUEST, "周数不能为空");
        if (StrUtil.isBlank(weekDay)) throw new CustomException(ResCodeEnum.BAD_REQUEST, "星期不能为空");
        if (StrUtil.isBlank(orderNum)) throw new CustomException(ResCodeEnum.BAD_REQUEST, "课程顺序不能为空");
        if (StrUtil.isBlank(grade)) throw new CustomException(ResCodeEnum.BAD_REQUEST, "年级不能为空");
        if (StrUtil.isBlank(stage)) throw new CustomException(ResCodeEnum.BAD_REQUEST, "学期不能为空");
        if (StrUtil.isBlank(schoolYear)) throw new CustomException(ResCodeEnum.BAD_REQUEST, "学年不能为空");

        QueryWrapper<Course> courseTimeWrapper = new QueryWrapper<>();
        courseTimeWrapper.eq(courseDTO.getIsDelete() != null, "is_delete", courseDTO.getIsDelete());
        courseTimeWrapper.eq("work_id", workId);
        // courseTimeWrapper.eq("work_id", workId);

        List<Course> courseTimeList = list(courseTimeWrapper);

        if (courseTimeList.size() != 0) {
            for (Course item : courseTimeList) {
                boolean isSameWeek = judgeSameNum(week, item.getWeek()) && judgeSameNum(weekDay, item.getWeekDay()) && judgeSameNum(orderNum, item.getOrderNum());
                boolean isSameYear = stage.equals(item.getStage().toString()) && schoolYear.equals(item.getSchoolYear());
                // boolean isSameYear = grade.equals(item.getGrade().toString()) && stage.equals(item.getStage().toString()) && schoolYear.equals(item.getSchoolYear());
                boolean isSameTeachClass = teachClass.equals(item.getTeachClass()) && stage.equals(item.getStage().toString()) && schoolYear.equals(item.getSchoolYear());
                //每学年学期的教学班唯一，不同的学年学期教学班可重复

                if (isSameWeek && isSameYear && isAdd)
                    throw new CustomException(ResCodeEnum.BAD_REQUEST, "该教师在该时间段已有课程");
                // if ((isAdd && isSameTeachClass) || isSameWeek && isSameYear && isSameTeachClass || !isSameWeek && !isSameYear && isSameTeachClass)
                if ((isAdd && isSameTeachClass) || (!isAdd && isSameTeachClass && !item.getId().equals(courseDTO.getId())))
                    throw new CustomException(ResCodeEnum.BAD_REQUEST, "该教学班已存在");
            }
        }

        Course course = new Course();
        BeanUtil.copyProperties(courseDTO, course);
        String nowTime = df.format(new Date());
        course.setCreateTime(nowTime);
        if(isAdd && StrUtil.isBlank(courseDTO.getColor())) course.setColor(colorList[random.nextInt(colorList.length)]);  //设置随机颜色
        boolean courseFlag = saveOrUpdate(course);
        boolean coManageFlag = false;
        boolean scoreManageFlag = false;
        //添加课程的同时，也向课程管理表和分数录入管理表中添加
        if(courseFlag && isAdd) {
            QueryWrapper<Course> wrapper = new QueryWrapper<>();
            wrapper.eq("create_time",nowTime);
            wrapper.select("id");
            List<Course> list = list(wrapper);
            if(list.size() != 1) throw new CustomException(ResCodeEnum.BAD_REQUEST, "错误地存在多个该创建时间的课程信息");

            String originTime = "1970-01-01 00:00:00";
            CoManage coManage = new CoManage();
            coManage.setCourseId(list.get(0).getId());
            coManage.setBeginTime(originTime);
            coManage.setEndTime(originTime);
            coManageFlag = coManageService.saveOrUpdate(coManage);

            ScoreManage scoreManage = new ScoreManage();
            scoreManage.setCourseId(list.get(0).getId());
            scoreManage.setBeginTime(originTime);
            scoreManage.setEndTime(originTime);
            scoreManageFlag = scManageService.saveOrUpdate(scoreManage);
        }
        return ResData.success(courseFlag && coManageFlag && scoreManageFlag);
    }

    //批量删除课程信息
    public ResData<Boolean> falseDeleteCourseByIds(List<String> idList) {
        QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", idList);
        List<Course> list = list(queryWrapper);
        // List<Course> list = courseService.list(queryWrapper);

        for (Course entity : list) {
            entity.setIsDelete(1);
        }

        return ResData.success(updateBatchById(list), "删除成功");
        // return ResData.success(courseService.updateBatchById(list), "删除成功");
    }

    //查询教师所有课程(教师首页)
    public ResData<ArrayList<TchCoYearVO>> findTchCoYear(String workId) {
        if (StrUtil.isBlank(workId)) throw new CustomException(ResCodeEnum.BAD_REQUEST, "工号不能为空");

        QueryWrapper<Course> wrapper = new QueryWrapper<>();
        wrapper.eq("work_id", workId);
        wrapper.select("stage","grade","teach_class","school_year");
        List<Course> list = list(wrapper);

        ArrayList<TchCoYearVO> tchCoYearVOList = new ArrayList<>();
        for (Course course : list) {
            TchCoYearVO tchCoYearVO = new TchCoYearVO();
            tchCoYearVO.setSchoolYear(course.getSchoolYear());
            tchCoYearVO.setGrade(course.getGrade());
            tchCoYearVO.setStage(course.getStage());
            tchCoYearVO.setTeachClass(course.getTeachClass());
            tchCoYearVOList.add(tchCoYearVO);
        }
        return ResData.success(tchCoYearVOList);
    }

    //查询所有课程的学年数组
    public ResData<LinkedHashSet<String>> findAllCourseSchoolYear() {
        QueryWrapper<Course> wrapper = new QueryWrapper<>();
        LinkedHashSet<String> schoolYearList = new LinkedHashSet<>();
        wrapper.select("school_year");
        wrapper.orderByDesc("school_year");
        List<Course> courseList = list();
        for(Course course: courseList) schoolYearList.add(course.getSchoolYear());

        return ResData.success(schoolYearList);
    }

    //查询教师所有课程所在的学年学期年级
    public ResData<TchCoYearListVO> findTchCoYearList(String workId) {
        if (StrUtil.isBlank(workId)) throw new CustomException(ResCodeEnum.BAD_REQUEST, "工号不能为空");

        QueryWrapper<Course> wrapper = new QueryWrapper<>();
        wrapper.eq("work_id", workId);
        wrapper.select("grade","stage","school_year");
        List<Course> list = list(wrapper);

        HashSet<String> schoolYearList = new HashSet<>();
        HashSet<Integer> stageList = new HashSet<>();
        HashSet<Integer> gradeList = new HashSet<>();
        for (Course course : list) {
            schoolYearList.add(course.getSchoolYear());
            stageList.add(course.getStage());
            gradeList.add(course.getGrade());
        }
        TchCoYearListVO tchCoYearListVO = new TchCoYearListVO();
        tchCoYearListVO.setSchoolYearList(schoolYearList);
        tchCoYearListVO.setStageList(stageList);
        tchCoYearListVO.setGradeList(gradeList);

        return ResData.success(tchCoYearListVO);
    }

    //根据课程id查询信息
    public ResData<CourseOneVO> findOne(String courseId) {
        if (StrUtil.isBlank(courseId)) throw new CustomException(ResCodeEnum.BAD_REQUEST, "课程id不能为空");

        QueryWrapper<Course> wrapper = new QueryWrapper<>();
        wrapper.eq("id", courseId);
        List<Course> list = list(wrapper);
        if (list.size() == 0) throw new CustomException(ResCodeEnum.BAD_REQUEST, "该id的课程不存在");
        if (list.size() > 1) throw new CustomException(ResCodeEnum.BAD_REQUEST, "错误地存在多个该id的课程");

        Course course = list.get(0);
        CourseOneVO courseOneVO = new CourseOneVO();
        BeanUtil.copyProperties(course, courseOneVO);
        courseOneVO.setOrderNum(course.getOrderNum().split(","));
        courseOneVO.setWeek(course.getWeek().split(","));
        courseOneVO.setWeekDay(course.getWeekDay().split(","));
        return ResData.success(courseOneVO);
    }

    //修改课程展示颜色(未使用)
    public ResData<Boolean> updateColor(String color,String courseId) {
        if(StrUtil.isBlank(color)) throw new CustomException(ResCodeEnum.BAD_REQUEST,"颜色值不能为空");
        if(StrUtil.isBlank(courseId)) throw new CustomException(ResCodeEnum.BAD_REQUEST,"课程id不能为空");

        Course course = new Course();
        course.setId(courseId);
        course.setColor(color);
        return ResData.success(saveOrUpdate(course));
    }

    //查询课表
    public ResData<ArrayList<CourseTableVO>> findCourseTable(CourseTableDTO courseTableDTO) {
        Integer week = courseTableDTO.getWeek();
        // Integer grade = courseTableDTO.getGrade();
        Integer stage = courseTableDTO.getStage();
        String schoolYear = courseTableDTO.getSchoolYear();
        String workId = courseTableDTO.getWorkId();
        String studentId = courseTableDTO.getStudentId();

        if(week == null) throw new CustomException(ResCodeEnum.BAD_REQUEST,"周数不能为空");
        // if(grade == null) throw new CustomException(ResCodeEnum.BAD_REQUEST,"年级不能为空");
        if(stage == null) throw new CustomException(ResCodeEnum.BAD_REQUEST,"期数不能为空");
        if(StrUtil.isBlank(schoolYear)) throw new CustomException(ResCodeEnum.BAD_REQUEST,"学年不能为空");
        if(StrUtil.isBlank(workId) && StrUtil.isBlank(studentId)) throw new CustomException(ResCodeEnum.BAD_REQUEST,"工号和学号不能同时为空");
        if(StrUtil.isNotBlank(workId) && StrUtil.isNotBlank(studentId)) throw new CustomException(ResCodeEnum.BAD_REQUEST,"工号和学号不能同时存在");

        ArrayList<String> courseIdList = new ArrayList<>();
        if(StrUtil.isNotBlank(studentId)) {
            QueryWrapper<CoSelection> wrapper = new QueryWrapper<>();
            wrapper.eq("student_id",studentId);
            List<CoSelection> coSelectionList = coSelectionService.list(wrapper);
            if(coSelectionList.size() == 0) return ResData.success(new ArrayList<>());
            for (CoSelection entity: coSelectionList) courseIdList.add(entity.getCourseId());
        }

        QueryWrapper<Course> courseWrapper = new QueryWrapper<>();
        courseWrapper.like("week",week);
        // courseWrapper.eq("grade",grade);
        courseWrapper.eq("stage",stage);
        courseWrapper.eq("school_year",schoolYear);
        courseWrapper.in(courseIdList.size() != 0,"id",courseIdList);
        courseWrapper.eq(StrUtil.isNotBlank(workId),"work_id",workId);
        List<Course> courseList = list(courseWrapper);

        HashSet<String> workIdList = new HashSet<>();
        for (Course entity: courseList) workIdList.add(entity.getWorkId());
        QueryWrapper<Teacher> tchWrapper = new QueryWrapper<>();
        tchWrapper.in(workIdList.size() != 0,"work_id",workIdList);
        tchWrapper.select("name","work_id");
        List<Teacher> teacherList = teacherService.list(tchWrapper);

        ArrayList<CourseTableVO> courseTableVOList = new ArrayList<>();
        for (Course entity: courseList) {
            String tchName = "";
            for (Teacher teacher: teacherList) if(teacher.getWorkId().equals(entity.getWorkId())) tchName = teacher.getName();

            ArrayList<String> continuousOrderList;
            try {
                continuousOrderList = getContinuousOrder(entity.getOrderNum().split(","), 0, new ArrayList<>());
            } catch (Exception e) {
                e.printStackTrace();
                throw new CustomException(ResCodeEnum.SERVER_ERROR,"课表查询获取课程序号失败");
            }
            // ArrayList<Integer> smallCountList = getSmallCount(orderList, 0, new ArrayList<>());



            String[] weekDayList = entity.getWeekDay().split(",");
            for (String weekDay: weekDayList) {
                for (String continuousOrder: continuousOrderList) {
                    CourseTableVO courseTableVO = new CourseTableVO();
                    courseTableVO.setColor(entity.getColor());
                    courseTableVO.setCourseId(entity.getId());
                    courseTableVO.setCourseName(entity.getCourseName());
                    courseTableVO.setCourseCode(entity.getCourseCode());
                    courseTableVO.setPlace(entity.getPlace());
                    courseTableVO.setWorkId(entity.getWorkId());
                    courseTableVO.setTchName(tchName);
                    String[] orderList = continuousOrder.split("-");
                    int beginOrder = Integer.parseInt(orderList[0]);
                    courseTableVO.setOrderNum(beginOrder);
                    if(StrUtil.isBlank(orderList[1])) courseTableVO.setSmallCount(1);
                    else courseTableVO.setSmallCount(Integer.parseInt(orderList[1]) - beginOrder + 1);
                    if(StrUtil.isNotBlank(weekDay)) courseTableVO.setWeekDay(Integer.parseInt(weekDay));


                    courseTableVOList.add(courseTableVO);
                }
            }
        }
        return ResData.success(courseTableVOList);
    }

    //excel表导入课程信息
    public ResData<Boolean> courseImport(MultipartFile file) {
        if (file == null) throw new CustomException(ResCodeEnum.BAD_REQUEST, "文件不能为空");

        // ArrayList<Course> importList = new ArrayList<>();
        List<FileCourseVO> fileVOList;
        try {
            InputStream inputStream = file.getInputStream();
            ExcelReader excelReader = ExcelUtil.getReader(inputStream);
            fileVOList = excelReader.readAll(FileCourseVO.class);
            inputStream.close();
            excelReader.close();
            // System.out.println("=========="+fileVOList.toString());
            if(fileVOList.size() == 0) throw new CustomException(ResCodeEnum.BAD_REQUEST, "该表为空表,请检查");
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException(ResCodeEnum.SERVER_ERROR, "导入课程信息表格失败");
        }

        //得到workId,tchName,teachClass
        String uniqueSchoolYear = "";
        int uniqueStage = 0;
        int uniqueGrade = 0;
        ArrayList<HashMap<String,String>> infoMapList = new ArrayList<>();
        LinkedHashSet<String> workIdList = new LinkedHashSet<>();
        LinkedList<String> teachClassList = new LinkedList<>();

        for (int i = 0; i < fileVOList.size(); i++) {
            FileCourseVO fileVO = fileVOList.get(i);
            String courseCode = fileVO.getCourseCode();
            String openCollege = fileVO.getOpenCollege();
            String allowBand = fileVO.getAllowBand();
            String courseType = fileVO.getCourseType();
            String classHourType = fileVO.getClassHourType();
            String place = fileVO.getPlace();
            String courseName = fileVO.getCourseName();
            Integer maxPerson = fileVO.getMaxPerson();
            Double credit = fileVO.getCredit();
            Integer totalHours = fileVO.getTotalHours();
            String workId = fileVO.getWorkId();
            String tchName = fileVO.getTchName();
            String teachClass = fileVO.getTeachClass();
            Integer stage = toNumStage(fileVO.getStage());
            int schoolYearIndex = fileVO.getSchoolYear().indexOf("学年");
            if(schoolYearIndex == -1 || schoolYearIndex == 0) throw new CustomException(ResCodeEnum.BAD_REQUEST, "有课程学年为空或格式不正确,请检查");
            String schoolYear = fileVO.getSchoolYear().substring(0,schoolYearIndex);

            int gradeIndex = fileVO.getGrade().indexOf("级");
            if(gradeIndex == -1 || gradeIndex == 0) throw new CustomException(ResCodeEnum.BAD_REQUEST, "有课程年级为空或格式不正确,请检查");
            int grade = Integer.parseInt(fileVO.getGrade().substring(0,gradeIndex));

            if (StrUtil.isBlank(courseCode)) throw new CustomException(ResCodeEnum.BAD_REQUEST, "有课程代码为空,请检查");
            if (StrUtil.isBlank(openCollege)) throw new CustomException(ResCodeEnum.BAD_REQUEST, "有课程开课学院为空,请检查");
            if (StrUtil.isBlank(allowBand)) throw new CustomException(ResCodeEnum.BAD_REQUEST, "有课程面向对象为空,请检查");
            if (StrUtil.isBlank(courseType)) throw new CustomException(ResCodeEnum.BAD_REQUEST, "有课程开课类型为空,请检查");
            if (StrUtil.isBlank(classHourType)) throw new CustomException(ResCodeEnum.BAD_REQUEST, "有课程学时类型为空,请检查");
            if (StrUtil.isBlank(place)) throw new CustomException(ResCodeEnum.BAD_REQUEST, "有课程上课地点为空,请检查");
            if (StrUtil.isBlank(courseName)) throw new CustomException(ResCodeEnum.BAD_REQUEST, "有课程名称称为空,请检查");
            if (maxPerson == null) throw new CustomException(ResCodeEnum.BAD_REQUEST, "有课程任务人数为空,请检查");
            if (credit == null) throw new CustomException(ResCodeEnum.BAD_REQUEST, "有课程学分为空,请检查");
            if (totalHours == null) throw new CustomException(ResCodeEnum.BAD_REQUEST, "有课程总学时为空,请检查");
            if (StrUtil.isBlank(workId)) throw new CustomException(ResCodeEnum.BAD_REQUEST, "有教师工号为空,请检查");
            if (StrUtil.isBlank(teachClass)) throw new CustomException(ResCodeEnum.BAD_REQUEST, "有课程教学班为空,请检查");
            if (StrUtil.isBlank(tchName)) throw new CustomException(ResCodeEnum.BAD_REQUEST, "有教师姓名为空,请检查");
            if(i == 0) {
                uniqueSchoolYear = schoolYear;
                uniqueStage = stage;
                uniqueGrade = grade;
            }
            else {
                if(!uniqueSchoolYear.equals(schoolYear) || uniqueStage != stage || uniqueGrade!= grade) {
                    throw new CustomException(ResCodeEnum.BAD_REQUEST, "不支持一个表格中包含多种学年学期年级,请检查");
                }
            }

            HashMap<String, String> hashMap = new HashMap<>();
            hashMap.put("workId",workId);
            hashMap.put("tchName",tchName);
            hashMap.put("teachClass",teachClass);
            infoMapList.add(hashMap);
            workIdList.add(workId);
            teachClassList.addFirst(teachClass);
        }

        //排除工号不存在  和  工号与姓名不匹配 的情况
        QueryWrapper<Teacher> tchWrapper = new QueryWrapper<>();
        tchWrapper.in("work_id", workIdList);
        tchWrapper.select("work_id","name");
        List<Teacher> tchList = teacherService.list(tchWrapper);

        LinkedList<String> notExistWorkIdList = new LinkedList<>();
        LinkedList<String> notMatchTchList = new LinkedList<>();

        for (HashMap<String, String> hashMap : infoMapList) {
            // for (String workId : workIdList) if (!entity.getWorkId().equals(workId)) notExistWorkIdList.addFirst(workId);
            boolean existFlag = false;
             for (Teacher entity : tchList)
                if (entity.getWorkId().equals(hashMap.get("workId"))) {
                    existFlag = true;
                    if(!entity.getName().equals(hashMap.get("tchName"))) notMatchTchList.addFirst(hashMap.get("teachClass"));
                }
            if(!existFlag) notExistWorkIdList.addFirst(hashMap.get("workId"));
        }
        if (notExistWorkIdList.size() != 0)
            throw new CustomException(ResCodeEnum.BAD_REQUEST, "以下工号的教师不存在或不支持一个课程多个教师：", notExistWorkIdList.toString());
        if (notMatchTchList.size() != 0)
            throw new CustomException(ResCodeEnum.BAD_REQUEST, "以下教学班的教师工号与姓名不匹配或不支持一个课程多个教师：", notMatchTchList.toString());

        //排除同学年学期教学班已存在 的情况
        QueryWrapper<Course> wrapper = new QueryWrapper<>();
        wrapper.in("teach_class", teachClassList);
        wrapper.eq("school_year",uniqueSchoolYear);
        wrapper.eq("stage",uniqueStage);
        wrapper.select("teach_class");
        List<Course> courseList = list(wrapper);
        if (courseList.size() != 0) {
            LinkedList<String> sameTeachClassList = new LinkedList<>();
            for (Course entity : courseList) sameTeachClassList.addFirst(entity.getTeachClass());
            throw new CustomException(ResCodeEnum.BAD_REQUEST, "已存在如下同一学年学期的教学班：", sameTeachClassList.toString());
        }

        //排除同一教师上课时间冲突
        QueryWrapper<Course> sameTimeWrapper = new QueryWrapper<>();
        sameTimeWrapper.in("work_id", workIdList);
        sameTimeWrapper.select("teach_class","week","week_day","order_num","stage","school_year","work_id");
        List<Course> sameTimeList = list(sameTimeWrapper);
        // System.out.println("=========="+sameTimeList.toString());
        LinkedList<String> sameTimeTeachClassList = new LinkedList<>();

        LinkedHashSet<String> createTimeList = new LinkedHashSet<>();
        LinkedList<Course> saveCourseList = new LinkedList<>();
        for (FileCourseVO fileVO : fileVOList) {
            String time = fileVO.getTime();
            if (StrUtil.isBlank(time)) throw new CustomException(ResCodeEnum.BAD_REQUEST, "有课程上课时间为空,请检查");

            int weekDayIndex = time.indexOf("星期");
            int orderIndex = time.indexOf("第");
            int orderEndIndex = time.indexOf("节");
            int weekIndex = time.indexOf("{");
            int weekEndIndex = time.indexOf("周}");
            if (weekDayIndex == -1 || orderIndex == -1 || orderEndIndex == -1 || weekIndex == -1 || weekEndIndex == -1) {
                throw new CustomException(ResCodeEnum.BAD_REQUEST, "有课程上课时间格式不正确,请检查");
            }
            String[] weekDayList = time.substring(weekDayIndex, orderIndex).split(",");  //星期二,星期三
            String[] orderList = time.substring(orderIndex + 1, orderEndIndex).split(",");//2,5-6
            String[] weekList = time.substring(weekIndex + 1, weekEndIndex).split(",");//2,1-4

            StringBuilder weeDayStr = new StringBuilder();
            System.out.println("weekDayList------------" + Arrays.toString(weekDayList));
            for (String str : weekDayList) weeDayStr.append(toNumWeekDay(str)).append(",");
            String weekDay = weeDayStr.deleteCharAt(weeDayStr.length() - 1).toString();

            StringBuilder orderStr = new StringBuilder();
            for (String str : orderList) orderStr.append(toSimpleNum(str)).append(",");
            String orderNum = orderStr.deleteCharAt(orderStr.length() - 1).toString();

            StringBuilder weekStr = new StringBuilder();
            for (String str : weekList) weekStr.append(toSimpleNum(str)).append(",");
            String week = weekStr.deleteCharAt(weekStr.length() - 1).toString();

            for (Course entity : sameTimeList) {  //sameTimeList为空
                if(!entity.getWorkId().equals(fileVO.getWorkId())) continue;  //当excel表中的workId等于查出来的workId时才执行
                boolean isSameWeek = judgeSameNum(week, entity.getWeek())
                        && judgeSameNum(weekDay, entity.getWeekDay())
                        && judgeSameNum(orderNum, entity.getOrderNum());

                boolean isSameYear = entity.getStage().equals(toNumStage(fileVO.getStage())) && entity.getSchoolYear().equals(uniqueSchoolYear);
                System.out.println("==========isSameWeek："+isSameWeek + "=========isSameYear：" + isSameYear);
                if (isSameWeek && isSameYear) sameTimeTeachClassList.addFirst(fileVO.getTeachClass());
            }

            String nowTime = df.format(new Date());
            Course course = new Course();
            course.setWeek(week);
            course.setWeekDay(weekDay);
            course.setOrderNum(orderNum);
            course.setSchoolYear(uniqueSchoolYear);
            course.setGrade(uniqueGrade);
            course.setStage(uniqueStage);
            course.setCreateTime(nowTime);
            course.setColor(colorList[random.nextInt(colorList.length)]);
            createTimeList.add(nowTime);

            BeanUtils.copyProperties(fileVO, course, "schoolYear","grade","stage");
            saveCourseList.addFirst(course);
        }
        if(sameTimeTeachClassList.size() != 0) throw new CustomException(ResCodeEnum.BAD_REQUEST, "如下教学班的教师在同一时间已有课程",sameTimeTeachClassList.toString());


        boolean courseFlag = saveBatch(saveCourseList);
        if(!courseFlag) throw new CustomException(ResCodeEnum.BAD_REQUEST, "Excel已解析，但保存课程信息失败");

        QueryWrapper<Course> findSavedWrapper = new QueryWrapper<>();
        findSavedWrapper.in("create_time",createTimeList);
        findSavedWrapper.select("id");
        List<Course> savedList = list(findSavedWrapper);
        if(savedList.size() == 0) throw new CustomException(ResCodeEnum.BAD_REQUEST, "错误地存在多个该创建时间的课程信息");

        String originTime = "1970-01-01 00:00:00";
        LinkedList<CoManage> coManageList = new LinkedList<>();
        LinkedList<ScoreManage> scoreManageList = new LinkedList<>();
        for(Course course: savedList) {
            CoManage coManage = new CoManage();
            coManage.setCourseId(course.getId());
            coManage.setBeginTime(originTime);
            coManage.setEndTime(originTime);
            coManageList.addFirst(coManage);

            ScoreManage scoreManage = new ScoreManage();
            scoreManage.setCourseId(course.getId());
            scoreManage.setBeginTime(originTime);
            scoreManage.setEndTime(originTime);
            scoreManageList.addFirst(scoreManage);
        }

        boolean coManageFlag = coManageService.saveBatch(coManageList);
        if(!coManageFlag) throw new CustomException(ResCodeEnum.BAD_REQUEST, "已保存课程信息，但保存初始选课时间失败");

        boolean scoreManageFlag = scManageService.saveBatch(scoreManageList);
        if(!scoreManageFlag) throw new CustomException(ResCodeEnum.BAD_REQUEST, "已保存课程信息，但保存初始成绩录入时间失败");

        return ResData.success(true);
    }

    //导出课程信息
    public void courseExport(HttpServletResponse response, FindAllCourseDTO findAllCourseDTO) {
        QueryWrapper<Course> wrapper = WrapperUtils.buildAllCourseWrapper(findAllCourseDTO, new QueryWrapper<>());
        List<Course> entityList = list(wrapper);

        Integer courseIsBegin = findAllCourseDTO.getCourseIsBegin();
        Integer scoreIsBegin = findAllCourseDTO.getScoreIsBegin();

        //当仅有courseIsBegin时
        if (courseIsBegin != null && scoreIsBegin == null) {
            if (!(courseIsBegin == 0 || courseIsBegin == 1))
                throw new CustomException(ResCodeEnum.BAD_REQUEST, "courseIsBegin只能是0或1");
            LinkedList<String> courseIdList = new LinkedList<>();
            for (Course course : entityList) courseIdList.addFirst(course.getId());
            QueryWrapper<CoManage> coManageWrapper = new QueryWrapper<>();
            coManageWrapper.in(courseIdList.size() != 0, "course_id", courseIdList);
            List<CoManage> coManageList = coManageService.list(coManageWrapper);
            LinkedList<Course> newEntityList = new LinkedList<>();
            for (CoManage coManage : coManageList) {
                String beginTime = coManage.getBeginTime();
                String endTime = coManage.getEndTime();
                newEntityList = getNewCourseList(beginTime,endTime,courseIsBegin,newEntityList,entityList);
            }
            entityList = newEntityList;
        }
        //当仅有scoreIsBegin时
        if (scoreIsBegin != null && courseIsBegin == null) {
            if (!(scoreIsBegin == 0 || scoreIsBegin == 1))
                throw new CustomException(ResCodeEnum.BAD_REQUEST, "scoreIsBegin只能是0或1");
            LinkedList<String> courseIdList = new LinkedList<>();
            for (Course course : entityList) courseIdList.addFirst(course.getId());
            QueryWrapper<ScoreManage> scoreManageWrapper = new QueryWrapper<>();
            scoreManageWrapper.in(courseIdList.size() != 0, "course_id", courseIdList);
            List<ScoreManage> scManageList = scManageService.list(scoreManageWrapper);
            LinkedList<Course> newEntityList = new LinkedList<>();
            for (ScoreManage scManage : scManageList) {
                String beginTime = scManage.getBeginTime();
                String endTime = scManage.getEndTime();
                newEntityList = getNewCourseList(beginTime,endTime,scoreIsBegin,newEntityList,entityList);
            }
            entityList = newEntityList;
        }
        if (scoreIsBegin != null && courseIsBegin != null) throw new CustomException(ResCodeEnum.BAD_REQUEST, "courseIsBegin和scoreIsBegin只能是0或1");

        //1. 所有学生列表，每一项处理后拷贝到 ExportVO的列表中
        LinkedHashSet<String> workIdList = new LinkedHashSet<>();
        ArrayList<FileCourseVO> exportVOList = new ArrayList<>();
        for (int i = 0; i < entityList.size(); i++) {
            Course entity = entityList.get(i);
            workIdList.add(entity.getWorkId());
            FileCourseVO exportVO = new FileCourseVO();
            String week = toChineseCourseOrder("", entity.getWeek(), "周");
            String orderNum = toChineseCourseOrder("第", entity.getOrderNum(), "节");
            String weekDay = toChineseWeekDay(entity.getWeekDay());

            exportVO.setOrder(i + 1);
            exportVO.setTime(weekDay + orderNum + "{" + week + judgeBiweekly(entity.getWeek()) + "}");
            exportVO.setSchoolYear(entity.getSchoolYear() + "学年");
            exportVO.setStage(toChineseStage(entity.getStage().toString()));
            exportVO.setGrade(entity.getGrade() + "级");

            BeanUtils.copyProperties(entity, exportVO, "schoolYear", "grade", "stage");
            exportVOList.add(exportVO);
        }

        //填充教师姓名字段
        QueryWrapper<Teacher> tchWrapper = new QueryWrapper<>();
        tchWrapper.in("work_id", workIdList);
        tchWrapper.select("work_id", "name");
        List<Teacher> tchList = teacherService.list(tchWrapper);

        for (FileCourseVO fileVO : exportVOList) {

            for (Teacher teacher : tchList) {
                System.out.println(fileVO.getWorkId() + "  ---- " + teacher.getWorkId());
                if (fileVO.getWorkId().equals(teacher.getWorkId())) {
                    fileVO.setTchName(teacher.getName());
                    break;
                }
            }
        }

        //2. 在UserExportVO类中给每个属性用 @Alias(value = "中文名")的注解添加中文名

        try {
            //3. 用ExcelUtil获取 excelWriter对象
            ExcelWriter excelWriter = ExcelUtil.getWriter(true);

            //4.将UserExportVO的列表写入excelWriter中，并添加中文名表头
            excelWriter.write(exportVOList, true);

            //5.设置浏览器响应的格式
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
            String fileName = URLEncoder.encode("课程信息", "UTF-8");  //设置文件名称,并进行编码
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");  //将文件名设置到 response的 header中

            //6.用response来货如输出流
            ServletOutputStream outputStream = response.getOutputStream();

            //7. 将输出流刷新到 excelWriter对象中，并关闭输出流和excelWriter对象
            excelWriter.flush(outputStream, true);
            outputStream.close();
            excelWriter.close();
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException(ResCodeEnum.SERVER_ERROR,"导出课程信息表格失败");
        }
    }


    //工具方法
    //处理分页查课程的数据
    public CourseVO setCourseVO(Course entity, CourseVO VO) throws Exception {
        VO.setWeekDay(toChineseWeekDay(entity.getWeekDay()));
        VO.setOrderNum(toChineseCourseOrder("第",entity.getOrderNum(), "节"));
        VO.setWeek(toChineseCourseOrder("第",entity.getWeek(), "周") + judgeBiweekly(entity.getWeek()));
        VO.setGrade(VO.getGrade() + "级");
        VO.setStage(toChineseStage(VO.getStage()));
        VO.setSchoolYear(VO.getSchoolYear() + "学年");
        return VO;
    }

    private String toChineseWeekDay(String weekDay) {
        String[] splitList = weekDay.split(",");
        StringBuilder chineseWeekDay = new StringBuilder();
        for (int i = 0; i < splitList.length; i++) {
            switch (splitList[i]) {
                case "1":
                    chineseWeekDay.append("星期一");
                    break;
                case "2":
                    chineseWeekDay.append("星期二");
                    break;
                case "3":
                    chineseWeekDay.append("星期三");
                    break;
                case "4":
                    chineseWeekDay.append("星期四");
                    break;
                case "5":
                    chineseWeekDay.append("星期五");
                    break;
                case "6":
                    chineseWeekDay.append("星期六");
                    break;
                case "7":
                    chineseWeekDay.append("星期天");
                    break;
                default:
                    chineseWeekDay.append("星期错误");
                    break;
            }
            if (i + 1 != splitList.length) chineseWeekDay.append("、");
        }
        return chineseWeekDay.toString();
    }

    private Integer toNumWeekDay(String weekDay) {
        switch (weekDay) {
            case "星期一":
                return 1;
            case "星期二":
                return 2;
            case "星期三":
                return 3;
            case "星期四":
                return 4;
            case "星期五":
                return 5;
            case "星期六":
                return 6;
            case "星期天":
            case "星期日":
                return 7;
            default:
                throw new CustomException(ResCodeEnum.BAD_REQUEST, "有课程时间的星期设置不正确,请检查");
        }
    }

    public String toChineseStage(String stage) {
        switch (stage) {
            case "1":
                return "第一学期";
            case "2":
                return "第二学期";
            default:
                return "学期错误";
        }
    }

    private Integer toNumStage(String stage) {
        switch (stage) {
            case "第一学期":
                return 1;
            case "第二学期":
                return 2;
            default:
                throw new CustomException(ResCodeEnum.BAD_REQUEST, "有课程学期为空或格式不正确");
        }
    }

    private String toChineseCourseOrder(String startChart, String orderNum, String unit) {
        String[] orderList = orderNum.split(",");
        ArrayList<String> ChineseOrder = getContinuousOrder(orderList, 0, new ArrayList<>());

        return startChart + StringUtils.join(ChineseOrder, ",") + unit;
    }

    private String judgeBiweekly(String orderNum) {
        try {
            String[] orderList = orderNum.split(",");

            ArrayList<Integer> flagList = new ArrayList<>();
            for (String order : orderList) {
                if (Integer.parseInt(order) % 2 != 0) flagList.add(1);
                else flagList.add(2);
            }

            for (int i = 0; i < flagList.size(); i++) {
                if (i + 1 != flagList.size()) {
                    for (int j = i + 1; j < flagList.size(); j++) {
                        if (!(flagList.get(i).equals(flagList.get(j)))) return "";
                    }
                }
            }

            if (flagList.get(0) == 1) return "(单周)";
            else return "(双周)";
        }catch (Exception e) {
            e.printStackTrace();
            throw new CustomException(ResCodeEnum.SERVER_ERROR,"判断单双周失败");
        }
    }

    private String toSimpleNum(String numList) {
        try {
            String[] splitList = numList.split("-");
            if(splitList.length == 1) return splitList[0];
            else {
                int start = 0;
                int end = 0;
                if(StrUtil.isNotBlank(splitList[0])) start = Integer.parseInt(splitList[0]);
                if(StrUtil.isNotBlank(splitList[splitList.length-1])) end = Integer.parseInt(splitList[splitList.length-1]);
                if(start >= end) throw new CustomException(ResCodeEnum.BAD_REQUEST, "有课程时间的连续课程或周数设置不正确,请检查");
                StringBuilder numStr = new StringBuilder();
                for (int i = start; i <= end; i++) numStr.append(i).append(",");
                numStr.deleteCharAt(numStr.length()-1);
                return numStr.toString();
            }
        }catch (Exception e) {
            e.printStackTrace();
            throw new CustomException(ResCodeEnum.SERVER_ERROR,"转化为单一数字失败");
        }
    }

    private ArrayList<String> getContinuousOrder(String[] orderList, int beginIndex, ArrayList<String> ChineseOrder) {
        try {
            for (int i = beginIndex; i < orderList.length; i++) {
                int now = Integer.parseInt(orderList[i]);
                if (i + 1 != orderList.length) {

                    int next = Integer.parseInt(orderList[i + 1]);
                    if (next != now + 1) {
                        if (i == beginIndex) ChineseOrder.add(Integer.toString(now));
                        else ChineseOrder.add(orderList[beginIndex] + "-" + now);
                        return getContinuousOrder(orderList, i + 1, ChineseOrder);
                    }
                } else {
                    if (i == beginIndex) ChineseOrder.add(Integer.toString(now));
                    else ChineseOrder.add(orderList[beginIndex] + "-" + now);
                    return ChineseOrder;
                }
            }
            return ChineseOrder; //不会执行
        }catch (Exception e) {
            e.printStackTrace();
            throw new CustomException(ResCodeEnum.SERVER_ERROR,"判断是否连续数字关系失败");
        }
    }

    private ArrayList<HashMap<String,Integer>> getSmallCount(String[] orderList, int beginIndex, ArrayList<HashMap<String,Integer>> smallCountList) {
        for (int i = beginIndex; i < orderList.length; i++) {
            int now = Integer.parseInt(orderList[i]);
            int beginOrder = Integer.parseInt(orderList[beginIndex]);
            HashMap<String,Integer> hashMap = new HashMap<>();

            if (i + 1 != orderList.length) {
                int next = Integer.parseInt(orderList[i + 1]);
                if (next != now + 1) {
                    setSmallCountHashMap(beginIndex, smallCountList, i, now, beginOrder, hashMap);
                    return getSmallCount(orderList, i + 1, smallCountList);
                }
            } else {
                setSmallCountHashMap(beginIndex, smallCountList, i, now, beginOrder, hashMap);
                return smallCountList;
            }
        }
        return smallCountList; //不会执行
    }

    private void setSmallCountHashMap(int beginIndex, ArrayList<HashMap<String, Integer>> smallCountList, int i, int now, int beginOrder, HashMap<String, Integer> hashMap) {
        if (i == beginIndex) {
            hashMap.put("orderNum",now);
            hashMap.put("smallCount",1);
        }
        else {
            hashMap.put("orderNum",beginOrder);
            hashMap.put("smallCount",now - beginOrder + 1);
        }
        smallCountList.add(hashMap);
    }

    //判断是否是含有相同的数字
    private boolean judgeSameNum(String newStr, String oldStr) {
        String[] newList = newStr.split(",");
        String[] oldList = oldStr.split(",");

        for (String newItem : newList) {
            for (String oldItem : oldList) {
                if (oldItem.equals(newItem)) return true;
            }
        }
        return false;
    }

    private LinkedList<Course> getNewCourseList(String beginTime,String endTime,Integer flag,LinkedList<Course> newEntityList,List<Course> entityList) {
        String nowTime = df.format(new Date());
        if (flag == 1) {
            for (Course course : entityList) {
                if (CommonUtils.compareDate(nowTime, beginTime) > 0 && CommonUtils.compareDate(nowTime, endTime) < 0) {
                    newEntityList.addFirst(course);
                }
            }
        }
        if (flag == 0) {
            for (Course course : entityList) {
                if (!(CommonUtils.compareDate(nowTime, beginTime) > 0 && CommonUtils.compareDate(nowTime, endTime) < 0)) {
                    newEntityList.addFirst(course);
                }
            }
        }
        return newEntityList;
    }

    //返回空数据
    private ResData<PageResVO<CourseVO>> returnEmptyRes() {
        //如果任何一个为空，说明没有该学生，或者没有该课程。进而选课表中就不会有数据，就直接返回空。
        PageResVO<CourseVO> emptyPageResVO = new PageResVO<>();
        emptyPageResVO.setRows(new ArrayList<>());
        return ResData.success(emptyPageResVO);
    }
}
